<!--
  - Copyright (c) 2018.
  - 北京九思金信科技有限公司对该文件内容保留所有权利。
  - 未经许可，不得私自拷贝、传播、发布、引用该文件内容，违者将被追究法律责任。
  -->

<template>
  <div>
    <el-card style="overflow: auto;max-height: 450px">
      <el-row>
        <el-row>
          <el-input v-model="searchParam"
                    placeholder="请输入企业名称"
                    @keyup.enter.native="searchCust()"
                    class="fengbao_input"
                    style="float: left;width: 400px;box-shadow:-1px -1px #E6E8E8"/>
          <el-button size="small"
                     @click="searchCust()"
                     style="float: left;color:green;outline-color: green;border-color:green;padding: 8px;border-radius: 0px">
            搜索
          </el-button>
        </el-row>

        <el-row v-if="hits.length > 0" style="padding-top: 20px">
          <el-row>
            <el-col align="left">
              <span><b>相关信息列表</b></span>
            </el-col>
          </el-row>
          <el-col align="right">
            <ft-pagination :total="totalRowNum" :current-page="currentPage" :pageSize="pageSize" @pageChange="load">
              <el-row>
                <el-table :data="hits">
                  <el-table-column prop="名称" label="名称" align="left" inline></el-table-column>
                  <el-table-column prop="统一社会信用代码" label="统一社会信用代码" align="left" inline></el-table-column>
                  <el-table-column align="center">
                    <template slot-scope="scope">
                      <el-button type="text" @click="importData(scope.$index, hits)">一键导入</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-row>
            </ft-pagination>
          </el-col>
        </el-row>

      </el-row>

    </el-card>
  </div>
</template>

<script>
  import uuid from 'uuid'

  export default {
    name: "fengbao",
    data() {
      return {
        apikey: this.GLOBAL.apikey,
        customerId: "",
        currentPage: 1,
        pageSize: 8,
        totalRowNum: 0,
        searchParam: "",
        keyword: "",
        hits: [],
        company: {},
        industry: {},
        member: [],
        investor: [],
        shareholder: {},
        nianbao: [],
        corp: {
          customerId: '',
          customerName: '',
          identityType: '',
          identityNo: '',
          customerType: '',
          customerStatus: '',
          economicsProperty: '',
          industry: '',
          industryBig: '',
          province: '',
          // city: _body.company["省市"],
          legalRepresentative: '',
          establishmentDate: '',
          registeredAddress: '',
          registeredCurrencyId: '',
          registeredCaptital: '',
          operatingPeriodStart: '',
          operatingPeriodEnd: '',
          businessScope: '',
          totalAssests: '',
          operatoinRevenue: '',
          stockCode: '',
          actualAddress: '',
          actualPostcode: ''

        }
      }
    },
    methods: {
      data() {
        return {}
      },
      searchCust() {
        if (this.searchParam.trim() == "") {
          return
        }
        this.keyword = this.searchParam;
        this.$http.get('/joys-rest/fengbao/v1/company/search', {
          params: {
            apikey: this.apikey,
            from: this.currentPage * this.pageSize - this.pageSize,
            size: this.pageSize,
            keyword: this.keyword
          }
        }).then(resp => {
          this.hits = resp.body
          this.hits = this.hits.hits
          this.totalRowNum = resp.body.total
        }, resp => {
          this.$message.error(resp.body)
        })
      },
      load(pageIndex, pageSize) {
        this.currentPage = pageIndex
        this.pageSize = pageSize
        if (this.searchParam == "") {
          return;
        }
        this.$http.get('/joys-rest/fengbao/v1/company/search', {
          params: {
            apikey: this.apikey,
            from: this.currentPage * this.pageSize - this.pageSize,
            size: this.pageSize,
            keyword: this.keyword
          }
        }).then(resp => {
          this.hits = resp.body
          this.hits = this.hits.hits
          this.totalRowNum = resp.body.total
        }, resp => {
          this.$message.error(resp.body)
        })
      },
      importData(index, hits) {
        const _body = this
        _body.customerId = uuid()
        _body.corp.company_id = hits[index]["统一社会信用代码"]
        _body.getFengbaoData(_body)
      },
      //工商信息
      searchCompany(_body, company_id, resolve) {
        _body.$http.get('/joys-rest/fengbao/v1/company/' + company_id, {
          params: {
            apikey: _body.apikey
          }
        }).then(resp => {
          _body.company = resp.body
          _body.searchIndustry(_body, company_id, resolve)
        }, resp => {
          _body.$message.error(resp.body)
        });
      },
      //行业信息
      searchIndustry(_body, company_id, resolve) {
        _body.$http.get('/joys-rest/fengbao/v1/company/' + company_id + '/industry', {
          params: {
            apikey: _body.apikey
          }
        }).then(resp => {
          _body.industry = resp.body
          //封装保存客户对象
          Promise.all([
            new Promise(function (resolve1, reject) {
              _body.setCorpVO(_body, resolve1)
            }),
            new Promise(function (resolve1, reject) {
              if (_body.corp.stockCode != '') {
                _body.searchGgxx(_body, _body.corp.stockCode, resolve1);
              } else {
                _body.searchMember(_body, company_id, resolve1);
              }
            })]).then(arr => {
            resolve(1)
          })
        }, resp => {
          _body.$message.error(resp.body)
        });
      },
      //主要成员
      searchMember(_body, company_id, resolve) {
        _body.$http.get('/joys-rest/fengbao/v1/company/' + company_id + '/member', {
          params: {
            apikey: _body.apikey,
            from: 0,
            size: 50,
          }
        }).then(resp => {
          _body.member = resp.body.hits
          _body.setMenberVO(_body, resolve)
        }, resp => {
          _body.$message.error(resp.body)
        });
      },
      //高管信息
      searchGgxx(_body, stockCode, resolve) {
        _body.$http.get('/joys-rest/fengbao/v1/stock/' + stockCode + '/ggxx', {
          params: {
            apikey: _body.apikey,
            from: 0,
            size: 50,
          }
        }).then(resp => {
          _body.setGgxxVO(_body, resp.body, resolve)
        }, resp => {
          _body.$message.error(resp.body)
        });
      },
      //股东信息
      searchInvestor(_body, company_id, resolve) {
        _body.$http.get('/joys-rest/fengbao/v1/company/' + company_id + '/investor', {
          params: {
            apikey: _body.apikey,
            from: 0,
            size: 50,
          }
        }).then(resp => {
          _body.investor = resp.body.hits;
          _body.searchRelation(_body, company_id, resolve)
        }, resp => {
          _body.$message.error(resp.body)
        });
      },
      // 关联列表
      searchRelation(_body, company_id, resolve) {
        _body.$http.get('/joys-rest/fengbao/v1/company/' + company_id + '/relation_list', {
          params: {
            apikey: _body.apikey,
            from: 0,
            size: 50,
          }
        }).then(resp => {
          if (resp.body.shareholder && resp.body.shareholder.length > 0) {
            for (var i = 0; i < resp.body.shareholder.length; i++) {
              _body.shareholder[resp.body.shareholder[i].name] = resp.body.shareholder[i].crn
            }
          }
          _body.setInvestorVO(_body, resolve)
        }, resp => {
          _body.$message.error(resp.body)
        })
      },
      //年报
      searchNianbao(_body, company_id, resolve) {
        _body.$http.get('/joys-rest/fengbao/v1/company/' + company_id + '/nianbao', {
          params: {
            apikey: _body.apikey,
            from: 0,
            size: 50,
          }
        }).then(resp => {
          _body.nianbao = resp.body.hits
          _body.setNianbaoVO(_body, resolve)
        }, resp => {
          _body.$message.error(resp.body)
        });
      },
      //获取数据入口
      getFengbaoData(_body) {
        Promise.all([
          new Promise(function (resolve, reject) {
            _body.$options.methods.searchCompany(_body, _body.corp.company_id, resolve)
          }),
          new Promise(function (resolve, reject) {
            _body.$options.methods.searchInvestor(_body, _body.corp.company_id, resolve)
          }),
          new Promise(function (resolve, reject) {
            _body.$options.methods.searchNianbao(_body, _body.corp.company_id, resolve)
          })
        ]).then(arr => {
          _body.$emit('returnValue', {switchShow: 'corp', customerId: _body.corp.customerId, dialogTableVisible: false})
        })
        // _body.$options.methods.searchCompany(_body, _body.corp.company_id)
        //
        // _body.$options.methods.searchInvestor(_body, _body.corp.company_id)
        //
        // _body.$options.methods.searchNianbao(_body, _body.corp.company_id)
        // return Promise.resolve(_body)
      },
      //封装保存客户对象
      setCorpVO(_body, resolve) {
        _body.corp.customerId = _body.customerId
        _body.corp.customerName = _body.company["名称"]
        _body.corp.identityType = "SOCIAL_SECURITYCODE"
        _body.corp.identityNo = _body.company["统一社会信用代码"]
        _body.corp.customerType = "ENTERPRISE"
        _body.corp.customerStatus = ""
        _body.corp.economicsProperty = _body.convertToeconomicsProperty(_body.company["类型代码"])
        // _body.corp.economicsProperty = _body.convertToeconomicsProperty(_body.company["类型"])
        _body.corp.industry = _body.industry["行业门类"]
        _body.corp.industryBig = _body.industry["行业大类"]
        _body.corp.province = _body.company["省市"]
        // city: _body.company["省市"]
        _body.corp.legalRepresentative = _body.company["法定代表人"]
        _body.corp.establishmentDate = _body.company["成立日期"]
        _body.corp.registeredAddress = _body.company["地址"]
        _body.corp.registeredCurrencyId = this.changeCurrency(_body.company["注册资本币种"])
        _body.corp.registeredCaptital = _body.company["注册资本（万元）"]
        _body.corp.operatingPeriodStart = _body.company["经营期限自"]
        _body.corp.operatingPeriodEnd = _body.company["经营期限至"]
        _body.corp.businessScope = _body.company["经营范围"]
        if (_body.company["股票"].length > 0) {
          _body.corp.stockCode = _body.company["股票"][0]["代码"]
        }
        _body.corp.infoMenu = "tabInfo;tabShareholder;tabFinance;tabAtt"
        this.$http.post('/joys-rest/lss-customer/custInfo/corp/fengbao/save', _body.corp).then(resp => {
          _body.corp = resp.body
          resolve(1)
        }, resp => {
          this.$message.error(resp.body)
        })
      },
      //封装主要成员
      setMenberVO(_body, resolve) {
        for (var index in _body.member) {
          _body.member[index].customerId = _body.customerId
          _body.member[index].managerName = _body.member[index]["成员"]
          _body.member[index].managerType = "PERSONAL"
          _body.member[index].managerJob = _body.member[index]["职务"]
        }
        this.$http.post('/joys-rest/lss-customer/custInfo/manager/saveBatch', _body.member).then(resp => {
          resolve(2)
        }, resp => {
          this.$message.error(resp.body)
        })
      },
      //封装高管
      setGgxxVO(_body, resp, resolve) {

        let member = resp["监事会"].concat(resp["董事会"]).concat(resp["高管"])

        for (var index in member) {
          _body.member[index] = {
            customerId: _body.customerId,
            managerName: member[index]["姓名"],
            managerJob: member[index]["职务"],
            managerSex: _body.convertSex(member[index]["基本信息"].substring(0, 1)),
            managerType: "PERSONAL",
            managerMemberType: _body.convertManagerMemberType(member[index]["职务"]),
            managerEducationBackground: member[index]["基本信息"].substring(4, 12),
            managerResume: member[index]["简介"]
          }
        }
        this.$http.post('/joys-rest/lss-customer/custInfo/manager/saveBatch', _body.member).then(resp => {
          resolve(2)
        }, resp => {
          this.$message.error(resp.body)
        })
      },
      //封装股东
      setInvestorVO(_body, resolve) {
        for (var index in _body.investor) {
          _body.investor[index].customerId = _body.customerId
          _body.investor[index].shareholderName = _body.investor[index]["股东"]
          _body.investor[index].shareholderRelationType = "shareholder"
          if (_body.shareholder[_body.investor[index]["股东"]] && _body.shareholder[_body.investor[index]["股东"]].length > 0) {
            _body.investor[index].shareholderType = "ENTERPRISE"
            _body.investor[index].shareholderIdentityType = "SOCIAL_SECURITYCODE"
          } else {
            _body.investor[index].shareholderType = _body.investor[index]["股东类型"]
          }
          _body.investor[index].shareScale = _body.investor[index]["持股比"]
          _body.investor[index].shareholderIdentityNo = _body.shareholder[_body.investor[index]["股东"]]
          _body.investor[index].actualInvestmentForms = _body.investor[index]["认缴明细"][0]["认缴出资方式"]
          _body.investor[index].actualInvestmentCurrency = _body.investor[index]["认缴明细"][0]["认缴出资币种"]
          _body.investor[index].actualInvestmentCapital = ("" + _body.investor[index]["认缴明细"][0]["认缴出资额"]).replace(/[^0-9]/g, '')
          _body.investor[index].actualInvestmentDate = _body.investor[index]["认缴明细"][0]["认缴出资日期"]
        }
        this.$http.post('/joys-rest/lss-customer/custInfo/shareholder/saveBatch', _body.investor).then(resp => {
          resolve(2)
        }, resp => {
          this.$message.error(resp.body)
        })
      },
      //封装财报
      setNianbaoVO(_body, resolve) {
        if (_body.nianbao != '' && _body.nianbao.length != 0) {
          if (_body.nianbao[0]["资产状况信息"] != '' && _body.nianbao[0]["资产状况信息"] != null) {
            if (_body.nianbao[0]["资产状况信息"]["资产总额"]) {
              if (("" + _body.nianbao[0]["资产状况信息"]["资产总额"]).indexOf('万') >= 0) {
                var totalAssests = ("" + _body.nianbao[0]["资产状况信息"]["资产总额"]).replace(/[^0-9.]/g, '')
                //四舍五入保留两位小数
                _body.corp.totalAssests = "" + Math.round(Number(totalAssests) * 100) / 100
              } else {
                var totalAssests = ("" + _body.nianbao[0]["资产状况信息"]["资产总额"]).replace(/[^0-9.]/g, '')
                //转为万元保留两位小数
                _body.corp.totalAssests = "" + Math.round(Number(totalAssests) / 100) / 100
              }
            }
            if (_body.nianbao[0]["资产状况信息"]["营业总收入"]) {
              if (("" + _body.nianbao[0]["资产状况信息"]["资产总额"]).indexOf('万') >= 0) {
                var operatoinRevenue = _body.corp.operatoinRevenue = ("" + _body.nianbao[0]["资产状况信息"]["营业总收入"]).replace(/[^0-9.]/g, '')
                //四舍五入保留两位小数
                _body.corp.operatoinRevenue = "" + Math.round(Number(operatoinRevenue) * 100) / 100
              } else {
                var operatoinRevenue = ("" + _body.nianbao[0]["资产状况信息"]["营业总收入"]).replace(/[^0-9.]/g, '')
                //转为万元保留两位小数
                _body.corp.operatoinRevenue = "" + Math.round(Number(operatoinRevenue) / 100) / 100
              }
            }
          }

          if (_body.nianbao[0]["基本信息"] != '' && _body.nianbao[0]["基本信息"] != null) {
            _body.corp.actualAddress = _body.nianbao[0]["基本信息"]["企业通信地址"]
            _body.corp.actualPostcode = _body.nianbao[0]["基本信息"]["邮政编码"]
          }
        }
        resolve(3)
      },
      goBack() {
        this.$emit("returnValue", {switchShow: "cust-list"})
      },
      changeCurrency(val) {
        if (!val) {
          return "CNY"
        }
        if (val.indexOf("人民币") >= 0) {
          return "CNY"
        } else if (val.indexOf("欧元") >= 0) {
          return "USD"
        } else if (val.indexOf("美元") >= 0) {
          return "EUR"
        } else {
          return "CNY"
        }
      },
      //经济性质转换
      convertToeconomicsProperty(val) {
        //股份有限公司
        var limitedCompany = ["1211", "1212", "1213", "1219", "1221", "1222",
          "1223", "1229", "2211", "2212", "2213", "2219", "2221", "2222", "2223",
          "2229", "3300", "3400", "4330", "4340", "4700", "6210", "6220", "6230",
          "6240", "6250", "6260", "6290"]
        //国有企业
        var stateOwnedEnterprise = ["3100", "4110", "4210", "4310", "4410"]
        //集体企业
        var collectiveEnterprise = ["3200", "4120", "4220", "4320", "4420"]
        //私营企业
        var privateEnterprise = ["4531", "4532", "4533", "4540", "4551", "4552", "4553", "4560"]
        //外商投资企业
        var foreignInvested = ["5130", "5140", "5150", "5160", "5210", "5220",
          "5230", "5240", "5290", "5810", "5820", "5830", "5890",
          "7110", "7120", "7130", "7190", "7200", "7310", "7390"]
        //有限责任公司
        var limitedLiability = ["1110", "1121", "1122", "1123", "1130", "1140",
          "1151", "1152", "1153", "1190", "2110", "2121", "2122",
          "2123", "2130", "2140", "2151", "2152", "2153", "2190",
          "6110", "6120", "6130", "6140", "6150", "6160", "6170",
          "6190"]
        //其他
        var otherEconomicsProperty = ["3500", "4600", "5400", "5410", "5420", "5430",
          "5490", "5840", "6310", "6320", "6390", "6400", "6410",
          "6420", "6430", "6490", "6810", "6820", "6830", "6840",
          "6890", "9100", "9200", "9900"]
        //中外合资企业
        var sinoForeignJoint = ["5110", "5120", "5190", "5310", "5390"]
        //中外独资企业
        var foreignEnterprise = []
        //国外独资企业
        var foreignOwnedEnterprises = []
        if (stateOwnedEnterprise.indexOf(val) != -1) {
          return 'STATE_OWNED'
        }
        if (collectiveEnterprise.indexOf(val) != -1) {
          return 'COLLECTIVE'
        }
        if (limitedLiability.indexOf(val) != -1) {
          return 'LIMITED_LIABILITY'
        }
        if (limitedCompany.indexOf(val) != -1) {
          return 'LIMITED'
        }
        if (privateEnterprise.indexOf(val) != -1) {
          return 'PRIVATE_ENTERPRISE'
        }
        if (foreignInvested.indexOf(val) != -1) {
          return 'FOREIGN'
        }
        if (sinoForeignJoint.indexOf(val) != -1) {
          return 'SINO_FOREIGN_JOINT'
        }
        if (foreignEnterprise.indexOf(val) != -1) {
          return 'SINO_FOREIGN'
        }
        if (foreignOwnedEnterprises.indexOf(val) != -1) {
          return 'FOREIGN_OWNED'
        }
        if (otherEconomicsProperty.indexOf(val) != -1) {
          return 'OTHER_ECONOMICS'
        }
        return ''

      },
      //高管人员类别转换
      convertManagerMemberType(val) {
        if (!val) {
          return ''
        }
        if (val.indexOf('董事长') > -1) {
          return 'CHAIRMAN'
        }
        if (val.indexOf('总经理') > -1) {
          return 'GENERAL_MANAGER'
        }
        if (val.indexOf('财务') > -1) {
          return 'FINANCIAL_RESPONSIBILITY'
        }
        if (val.indexOf('监事长') > -1) {
          return 'SUPERVISOR'
        }
        return ''
      },
      //性别转换
      convertSex(val) {
        if (!val) {
          return ''
        }
        if (val == '男') {
          return 'MALE'
        }
        if (val == '女') {
          return 'FEMALE'
        }
        return ''
      }
    }
  }
</script>
<style>
  .fengbao_input .el-input__inner:focus {
    border-color: #b3b9b9;
  }

</style>
<style scoped>

</style>
